package com.iflytek.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iflytek.entity.Student;
import com.iflytek.entity.excel.StudentImportVO;
import com.iflytek.mapper.StudentMapper;
import com.iflytek.service.IStudentService;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.iai.v20200303.IaiClient;
import com.tencentcloudapi.iai.v20200303.models.CreatePersonRequest;
import com.tencentcloudapi.iai.v20200303.models.CreatePersonResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 周超
 * @since 2025-05-29
 */
@Slf4j
@Service
//@AllArgsConstructor
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {
    @Resource
    private StudentMapper studentMapper;
    @Override
    public boolean addStudentFace(String name, String className, MultipartFile file) {
        Student student = studentMapper.selectByName(name);


        // 根据班级名称和学生姓名查找学生,若不存在，则添加学生信息
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Student::getClassName, className).eq(Student::getName, name);
        queryWrapper.last("limit 1");
        Student student = this.getOne(queryWrapper);
        if (Objects.isNull(student)) {
            log.info("学生信息不存在，准备创建新学生人脸信息");
            student = new Student();
            student.setName(name);
            student.setClassName(className);
            student.setPersonId(className.hashCode() + "_" + name.hashCode());
            this.save(student);
        }
        //创建腾讯云人员库中的人员信息
        Credential credential = new Credential("AKIDkMlxvf9PSuEOL6e095oKelfNuERREpCQ", "ADJJNM8mPuCIML9yazAA250mMwSnz0ws");
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("iai.tencentcloudapi.com");
        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        // 实例化要请求产品的client对象,clientProfile是可选的
        IaiClient client = new IaiClient(credential, "ap-nanjing", clientProfile);
        // 实例化一个请求对象,每个接口都会对应一个request对象
        CreatePersonRequest req = new CreatePersonRequest();
        req.setGroupId("zjjxy_2025_zyzhsx");
        req.setPersonName(name);
        req.setPersonId(className.hashCode() + "_" + name.hashCode());
        try {
            // 获取文件字节数组并转为Base64编码
            byte[] fileBytes = file.getBytes();
            String base64Image = Base64.getEncoder().encodeToString(fileBytes);
            // 设置Base64编码的图片数据
            req.setImage(base64Image);

            log.info("创建学生人脸信息请求：{}", AbstractModel.toJsonString(req));
            // 返回的resp是一个CreateFaceResponse的实例，与请求对象对应
            CreatePersonResponse resp = client.CreatePerson(req);
            // 输出json格式的字符串回包
            log.info("创建学生人脸信息响应：{}", AbstractModel.toJsonString(resp));
        } catch (Exception e) {
            log.info("创建学生人脸信息失败: {}", e.getMessage(), e);
            return false;
        }
        return true;
    }

    @Override
    @Transactional
    public int importStudentInfo(MultipartFile file) {
        final List<Student> studentList = new ArrayList<>();
        try {
            EasyExcel.read(file.getInputStream(), StudentImportVO.class, new AnalysisEventListener<StudentImportVO>() {
                @Override
                public void invoke(StudentImportVO data, AnalysisContext context) {
                    log.info("解析到一条数据: {}", data);

                    Student student = new Student();
                    student.setName(data.getName());
                    student.setClassName(data.getClassName());
                    student.setPersonId(data.getClassName().hashCode() + "_" + data.getName().hashCode());
                    studentList.add(student);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext context) {
                    log.info("Excel解析完成，共{}条数据", studentList.size());
                }
            }).sheet().doRead();

            // 批量保存学生信息
            if (!studentList.isEmpty()) {
                this.saveBatch(studentList);
            }

            return studentList.size();
        } catch (Exception e) {
            log.error("导入学生信息失败: {}", e.getMessage(), e);
            throw new RuntimeException("导入学生信息失败", e);
        }
    }

    @Override
    public Student findByPersonId(String personId) {
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Student::getPersonId, personId);
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }
}
